import React, { useState, useCallback } from "react";
import { Link } from "react-router-dom";
import FoundationSymbol from "@icedesign/foundation-symbol";
import {
  Input,
  Checkbox,
  Grid,
  Form,
  Message,
  Upload,
  Button,
  Icon,
} from "@alifd/next";
// 引入编辑器组件
import BraftEditor from "braft-editor";
import { ContentUtils } from "braft-utils";

// 引入编辑器样式
import "braft-editor/dist/index.css";
import { useRequest } from "@/utils/request";
import { categoryAdd, uploadAction, downLoadUrl } from "@/config/dataSource";
import styles from "./index.module.scss";
const controls = [
  "bold",
  "italic",
  'text-align',
  "underline",
  "text-color",
  "separator",
  "font-size",
  "separator",
  "emoji"
];
const { Row } = Grid;
const FormItem = Form.Item;

function UserLogin(props) {
  const { loading, request } = useRequest(categoryAdd);

  const [editorState, setEditorState] = useState(
    BraftEditor.createEditorState(null)
  );
  const [value, setValue] = useState({
    validateCode: "",
  });
  function formChange(formValue) {
    setValue(formValue);
  }

  function handleSubmit(values, errors) {
    if (errors) {
      console.log("errors", errors);
      return;
    }
    addArticle(values);
  }

  function handleChange(editorState) {
    setEditorState(editorState);
  }

  async function addArticle(params) {
    try {
      const rsp = await request({
        data: { name: params.name, content: editorState.toHTML() },
      });
      // setValue(rsp);
      Message.success("添加成功");
      props.history.push("/articleList");
    } catch (err) {}
  }

  function onChange(info) {
    let name = "";
    if (info.length <= 0) {
      return;
    }
    let fileInfo = info[info.length - 1];
    if (fileInfo.response.result) {
      name = fileInfo.response.obj.name;
    } else {
      Message.success(fileInfo.response.errorMsg);
    }

    setEditorState(
      ContentUtils.insertMedias(editorState, [
        {
          type: "IMAGE",
          url: `${downLoadUrl}${name}`,
        },
      ])
    );
    console.log("onChange callback : ", info);
  }

  const extendControls = [
    {
      key: "antd-uploader",
      type: "component",
      component: (
        <Upload
          listType="text"
          action={uploadAction}
          accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
          // beforeUpload={beforeUpload}
          onChange={onChange}
        >
          <Icon
            style={{ marginTop: "10px", cursor: "pointer" }}
            type="upload"
          />
        </Upload>
      ),
    },
  ];

  return (
    <div className={styles.addArticle}>
      <Form value={value} onChange={formChange} style={{ width: "900px" }}>
        <FormItem required requiredMessage="必填" className={styles.formItem}>
          <Input name="name" placeholder="标题" />
        </FormItem>
        <FormItem required requiredMessage="必填" className={styles.formItem}>
          <div className="my-component" style={{ border: "1px solid #ccc" }}>
            <BraftEditor
              extendControls={extendControls}
              controls={controls}
              onChange={handleChange}
              value={editorState}
            />
          </div>
        </FormItem>
        <Row className={styles.formItem} style={{marginBottom:'30px'}}>
          <Form.Submit
            type="primary"
            validate
            disabled={loading}
            onClick={handleSubmit}
            className={styles.submitBtn}
          >
            {loading ? "保存中..." : "保存"}
          </Form.Submit>
        </Row>
      </Form>
    </div>
  );
}

export default UserLogin;
